
#include "EventListener.h"
#include "EventDispatch.h"

EventListener::EventListener()
    : dispatch_(nullptr){
}

EventListener::~EventListener()
{
    this->DisConnect();
}

void EventListener::SetProcess(const std::string& name)
{
    this->RemoveProcess(name);
}

void EventListener::ProcessEvent(const std::string& name, EventBase* event)
{
    auto it = this->funcList_.find(name);
    if(it != this->funcList_.end())
        it->second(event);
}

void EventListener::Connect(EventDispatch* dispatch)
{
    if(dispatch != nullptr)
    {
        this->DisConnect();
        this->dispatch_ = dispatch;
        dispatch->AddListener(this);
    }
}

void EventListener::DisConnect()
{
    if(this->dispatch_ != nullptr)
    {
        // 只在非派发期间允许移除，派发期的移除会被延迟到派发结束后移除
        if(!this->dispatch_->IsDispatching())
            this->dispatch_->RemoveListener(this);
        this->dispatch_ = nullptr;
    }
}

bool EventListener::IsValid() const
{
    return !this->funcList_.empty() && this->dispatch_ != nullptr;
}

bool EventListener::CheckEvent(const std::string& name) const
{
    auto it = this->funcList_.find(name);
    return (it != this->funcList_.end());
}

std::vector<std::string> EventListener::GetEventList() const
{
    std::vector<std::string> list;
    for(auto& it : this->funcList_)
        list.push_back(it.first);
    return list;
}

bool EventListener::RemoveProcess(const std::string& name)
{
    auto it = this->funcList_.find(name);
    if(it != this->funcList_.end())
    {
        this->funcList_.erase(it);
        return true;
    }
    return false;
}

void EventListener::Clear()
{
    this->funcList_.clear();
}


